package com.city.java.abnormal_records.controller;

import com.city.java.abnormal_records.pojo.entity.AbnormalRecords;
import com.city.java.abnormal_records.service.AbnormalRecordService;
import com.city.java.base.response.JsonResult;
import com.city.java.base.utils.PageVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 异常记录控制器
 * RestController注解: 组合注解，相当于@Controller + @ResponseBody
 * Api注解: Knife4j文档中模块的显示名称
 * RequestMapping注解: 设置统一的请求路径前缀
 */
@Slf4j
@Api(tags = "10.异常记录模块")
@RestController
@RequestMapping("/api/abnormal-records")
public class AbnormalRecordController {

    @Autowired
    private AbnormalRecordService abnormalRecordService;

    /**
     * 添加异常记录
     * PostMapping注解: 处理POST请求
     * ApiOperation注解: Knife4j文档中接口的显示名称
     */
    @PostMapping("/add")
    @ApiOperation(value = "添加异常记录", notes = "添加新异常记录信息")
    public JsonResult addAbnormalRecord(
            @ApiParam(value = "异常记录信息", required = true)
            @RequestBody AbnormalRecords abnormalRecord) {
        log.info("接收到添加异常记录请求: {}", abnormalRecord);
        return abnormalRecordService.addAbnormalRecord(abnormalRecord);
    }

    /**
     * 根据异常记录ID查询异常记录
     * GetMapping注解: 处理GET请求
     * PathVariable注解: 获取路径中的参数
     */
    @GetMapping("/select/id/{abnormalId}")
    @ApiOperation(value = "根据ID查询异常记录", notes = "根据异常记录ID查询异常记录详细信息")
    public JsonResult getAbnormalRecordById(
            @ApiParam(value = "异常记录ID", required = true, example = "1")
            @PathVariable Long abnormalId) {
        log.info("接收到根据ID查询异常记录请求: ID={}", abnormalId);
        return abnormalRecordService.getAbnormalRecordById(abnormalId);
    }

    /**
     * 根据异常类型查询异常记录列表
     */
    @GetMapping("/select/type/{abnormalType}")
    @ApiOperation(value = "根据异常类型查询异常记录", notes = "根据异常类型查询异常记录列表")
    public JsonResult getAbnormalRecordsByAbnormalType(
            @ApiParam(value = "异常类型", required = true, example = "门禁系统")
            @PathVariable String abnormalType) {
        log.info("接收到根据异常类型查询异常记录请求: abnormalType={}", abnormalType);
        return abnormalRecordService.getAbnormalRecordsByAbnormalType(abnormalType);
    }

    /**
     * 查询所有异常记录列表
     */
    @GetMapping("/quarry")
    @ApiOperation(value = "查询所有异常记录", notes = "查询所有异常记录列表")
    public JsonResult getAllAbnormalRecords() {
        log.info("接收到查询所有异常记录请求");
        return abnormalRecordService.getAllAbnormalRecords();
    }

    /**
     * 根据异常记录ID删除异常记录
     * DeleteMapping注解: 处理DELETE请求
     */
    @DeleteMapping("/delete/id/{abnormalId}")
    @ApiOperation(value = "根据ID删除异常记录", notes = "根据异常记录ID删除异常记录")
    public JsonResult deleteAbnormalRecordById(
            @ApiParam(value = "异常记录ID", required = true, example = "1")
            @PathVariable Long abnormalId) {
        log.info("接收到根据ID删除异常记录请求: ID={}", abnormalId);
        return abnormalRecordService.deleteAbnormalRecordById(abnormalId);
    }

    /**
     * 更新异常记录信息
     * PutMapping注解: 处理PUT请求
     */
    @PutMapping("/update")
    @ApiOperation(value = "更新异常记录信息", notes = "更新异常记录详细信息")
    public JsonResult updateAbnormalRecord(
            @ApiParam(value = "异常记录信息", required = true)
            @RequestBody AbnormalRecords abnormalRecord) {
        log.info("接收到更新异常记录信息请求: {}", abnormalRecord);
        return abnormalRecordService.updateAbnormalRecord(abnormalRecord);
    }

    @GetMapping("/select")
    public JsonResult select(AbnormalRecords abnormalRecords){
        log.debug("准备查询异常记录: {}", abnormalRecords);
        PageVO<AbnormalRecords> pageVO = abnormalRecordService.select(abnormalRecords);
        return JsonResult.ok(pageVO);
    }
    /**
     * 查询最新未处理异常记录（用于首页弹窗提醒）
     */
    @GetMapping("/select/latest-unprocessed")
    @ApiOperation(value = "查询最新未处理异常记录", notes = "查询最近创建的未处理异常记录用于首页弹窗提醒")
    public JsonResult getLatestUnprocessedAbnormalRecords() {
        log.debug("查询最新未处理异常记录用于弹窗提醒");

        try {
            AbnormalRecords queryCondition = new AbnormalRecords();
            queryCondition.setStatus(AbnormalRecords.ProcessingStatus.pending);
            PageVO<AbnormalRecords> pageVO = abnormalRecordService.select(queryCondition);
            List<AbnormalRecords> allRecords = pageVO.getList();

            // 过滤出最近2分钟内的记录
            LocalDateTime twoMinutesAgo = LocalDateTime.now().minusMinutes(2);
            List<AbnormalRecords> latestRecords = allRecords.stream()
                    .filter(record -> record.getCreatedAt().isAfter(twoMinutesAgo))
                    .collect(Collectors.toList());

            log.info("查询最新未处理异常记录成功: 记录数量={}", latestRecords.size());
            return JsonResult.ok(latestRecords);
        } catch (Exception e) {
            log.error("查询最新未处理异常记录失败", e);
            return new JsonResult(500, "查询最新未处理异常记录失败");
        }
    }
}
